package com.junko.api.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.junko.api.tool.ToolJWT;
import com.junko.core.base.BaseController;
import com.junko.core.tool.ToolDateTime;
import com.junko.model.app.User;
import com.junko.service.app.IUserService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

public class BaseApiController extends BaseController{

    @Resource
    private IUserService userService;

    /**
     * 根据token获取当前用户
     *
     * @return
     */
    protected User getCurrentUser() {
        //获取请求头中的token
        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //解析token
        DecodedJWT decodedJWT = ToolJWT.verify(token);
        if (decodedJWT == null) {
            return null;
        }
        //获取token失效时间点
        Date date = decodedJWT.getExpiresAt();
        //token过期了
        if (date != null && ToolDateTime.compare(date, new Date()) <= 0) {
            return null;
        }
        //获取id，并返回对应的用户
        String id = decodedJWT.getClaims().get("id").asString();
        return userService.selectByPrimaryKey(id);
    }

    /**
     * 根据token获取当前用户id
     *
     * @return
     */
    protected String getCurrentUserId() {
        //获取请求头中的token
        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //解析token
        DecodedJWT decodedJWT = ToolJWT.verify(token);
        if (decodedJWT == null) {
            return null;
        }
        //获取token失效时间点
        Date date = decodedJWT.getExpiresAt();
        //token过期了
        if (date != null && ToolDateTime.compare(date, new Date()) <= 0) {
            return null;
        }
        //返回id
        return decodedJWT.getClaims().get("id").asString();
    }
}